let body = document.querySelector("body");

body.addEventListener("click", function (evt) {
  target = evt.target;

  //---------------获得数据-------------------------
  if (target.className.includes("get")) {
    let xhr = new XMLHttpRequest();

    xhr.open("GET", "http://localhost:3000/users");
    xhr.onload = function () {
      if (xhr.status == 200 || xhr.status == 304) {
        let arr = JSON.parse(xhr.responseText);
        arr.forEach(function (item) {
          console.log(item.uid);
        });
      }
    };
    xhr.send();
  }
  //---------------上传数据-------------------------
  //使用json-server时json数据加上id
  if (target.className.includes("post")) {
    let xhr = new XMLHttpRequest();

    xhr.open("POST", "http://localhost:3000/users");
    xhr.onload = function () {
      if (xhr.status == 201) {
        console.log("连接成功");
      }
    };

    // 声明上传格式
    // xhr.setRequestHeader("Content-Type", "application/json");//JSON数据上传
    // xhr.send(
    //   JSON.stringify({
    //     uid: "65441",
    //     password: "asdcas3",
    //   })
    // );
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(`uid=32131&&passwoar=1230`);
  }
  //---------------修改数据-------------------------
  if (target.className.includes("patch")) {
    let xhr = new XMLHttpRequest();
    xhr.open("PATCH", "http://localhost:3000/users/2");
    xhr.onload = function () {
      if (xhr.status == 200 || xhr.status == 304) {
      }
    };
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.send(`uid=22222`);
  }
  if (target.className.includes("delete")) {
    console.log("delete");
  }


  //---------------修改数据-------------------------
  if (target.className.includes("put")) {
    // 在url里加上id号
    let xhr = new XMLHttpRequest();

    xhr.open("PUT", "http://localhost:3000/users/1");
    xhr.onload = function () {
      if (xhr.status == 200) {
        console.log("连接成功");
      }
    };
    xhr.setRequestHeader("Content-Type", "application/json");//JSON数据上传
    xhr.send(JSON.stringify({
        "uid":"11111",  
        "password":"11111"
    }));
  }
  //---------------删除数据-------------------------
  if (target.className.includes("delete")) {
    // 在url里加上id号
    let xhr = new XMLHttpRequest();

    xhr.open("DELETE", "http://localhost:3000/users/1");
    xhr.onload = function () {
      if (xhr.status == 200) {
        console.log("连接成功");
      }
    };

    xhr.send();
  }
});
